package rest

import (
	"encoding/json"
	"gitee.com/cooge/impush/config"
	"gitee.com/cooge/impush/core"
	"gitee.com/cooge/impush/message"
	"gitee.com/cooge/impush/user"
	log "github.com/sirupsen/logrus"
	"net/http"
	"strconv"
)

func root(w http.ResponseWriter, re *http.Request) {
	core.AddInfo("USER_NUM", user.AllLen())
	mssg, err := json.Marshal(core.GetInfo())
	if err == nil {
		w.Write(mssg)
	}
}

func sendMsg(w http.ResponseWriter, re *http.Request) {
	id := re.FormValue("id")
	msg := re.FormValue("msg")
	if len(id) == 0 || len(msg) == 0 {
		w.Write([]byte(`{"code":404,"msg":"id is blank"}`))
	} else {
		mm := message.GetSystemMessage(id, msg)
		_, err := core.SendMessage(id, mm)
		if err != nil {
			w.Write([]byte(err.Error()))
		} else {
			w.Write([]byte(message.SUCCESS))
		}
	}
}

func queryuser(w http.ResponseWriter, r *http.Request) {
	id := r.FormValue("id")
	if len(id) == 0 {
		w.Write([]byte(`{"code":404,"msg":"id is blank"}`))
	} else {
		us := core.GetUser(id)
		u := make([]string, 0)
		if us != nil && len(us) > 0 {
			for _, v := range us {
				uc, ok := v.(core.UserConn)
				if ok {
					u = append(u, uc.GetUser())
				}
			}
		}
		mssg, err := json.Marshal(u)
		if err == nil {
			w.Write(mssg)
		}
	}
}

func onlineuser(w http.ResponseWriter, r *http.Request) {
	start := r.FormValue("start")
	s, err := strconv.Atoi(start)
	if err != nil {
		s = 0
	}
	num := r.FormValue("num")
	n, err := strconv.Atoi(num)
	if err != nil {
		n = 0
	}
	sysinfo := make(map[string]interface{})
	sysinfo["id"] = user.AllLen()
	us := user.GetKeyArray(s, n)
	sysinfo["user"] = us
	mssg, err := json.Marshal(sysinfo)
	if err == nil {
		w.Write(mssg)
	}
}

/**
  测试使用,不建议对外
*/

func deleteLocalUser(w http.ResponseWriter, r *http.Request) {
	id := r.FormValue("id")
	user.DeleteKey(id)
	w.Write([]byte(`{"code":200,"msg":"ok"}`))
}

func Start() {
	start()
}

func start() {
	http.HandleFunc("/", root)
	core.AddInfo("HTTP_PORT", config.HTTP_PORT)
	http.HandleFunc("/onlineuser", onlineuser)

	if config.LOG_OPEN {
		http.HandleFunc("/deleteLocalUser", deleteLocalUser)
	}

	http.HandleFunc("/sendmsg", sendMsg)
	http.HandleFunc("/queryuser", queryuser)
	err := http.ListenAndServe(":"+strconv.Itoa(config.HTTP_PORT), nil)
	if err != nil {
		log.Panic("启动失败", err)
	}
}
